package com.foreveross.dao.imp;

import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import com.foreveross.common.SQLUtil;
import com.foreveross.dao.DDManagerDAO;
import com.foreveross.dao.SysRoleManagerDAO;
import com.foreveross.vo.HrCode;
import com.foreveross.vo.SysRole;

@Component("sysRoleManagerDAO")
public class SysRoleManagerDAOImp extends SQLUtil implements SysRoleManagerDAO {

	public List<SysRole> findSysRoleList(String name, int pageIndex,
			int pageSize) throws Exception {
		StringBuffer queryString = new StringBuffer(
				"select model from SysRole model where 1=1 ");
		if (!"".equals(name) && null != name) {
			queryString.append(" and model.name like '%" + name + "%'");
		}
		queryString.append(" order by model.id desc");
		return (List<SysRole>) findObjectAll(queryString.toString(), pageIndex,
				pageSize);
	}

	@Override
	public long findSysRoleListCount(String name) throws Exception {
		StringBuffer queryString = new StringBuffer(
				"select count(*) from SysRole model where 1=1 ");
		if (!"".equals(name) && null != name) {
			queryString.append(" and model.name like '%" + name + "%'");
		}
		return (Long) findObjectAll(queryString.toString()).get(0);
	}

	@Override
	public void deleteSysRole(String id) throws Exception {
		final String sql = "delete from SysRole t where t.id='" + id + "'";
		updateObejctByHql(sql);
	}

	@Override
	public JSONArray getUserRoleList(String userId) throws Exception {
		String sql = "select r.id,r.name, ur.id as urid from sys_role r left join (select * from sys_user_role where sys_user_id='"
				+ userId + "') ur on r.id=ur.sys_role_id";
		JSONArray array = new JSONArray();
		List list = this.findObejctBySQL(sql,null);
		for (int i = 0; i < list.size(); i++) {
			Object[] s = (Object[]) list.get(i);
			JSONObject obj = new JSONObject();
			obj.put("id", s[0]);
			obj.put("text", s[1]);
			if (s[2] != null &&! "".equals(s[2]))
				obj.put("checked", true);
			array.add(obj);
		}
		return array;
	}

}
